const koa = require('koa')
const routers = require('./routes/index')
const bodyParser = require('koa-body');
const cors = require('koa2-cors');
const koaStatic = require('koa-static');
const NodeMediaServer = require('node-media-server');
const path = require('path')
const fs = require('fs')

// 配置https服务
const https = require('https')
const sslify = require('koa-sslify').default

// 上传文件服务
require('./utils/upload/upload')

// socket服务
require('./socket/index')

const config = require('./config/config.js')
const routerResponse =  require('./middleware/routerResponse')

// 直播服务
var nms = new NodeMediaServer(config.rtmpConfig)
nms.run();

const app = new koa()

// 配置https的服务
const options = {
  cert: fs.readFileSync(path.join(__dirname, 'cert', 'certificate.pem')),
  key: fs.readFileSync(path.join(__dirname, "cert", "privatekey.pem"))
}

app.use(sslify())

https.createServer(options, app.callback()).listen(config.port, (err) => {
  if (err) {
    console.log('服务启动出错', err);
  } else {
    console.log('主端口：',config.port,`running...`);
  }	
});

// 中间件
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text'],
  multipart: true // 是否支持 multipart-formdate 的表单
}))

app.use(routerResponse())


// 解决跨域   初始化路由中间件
app.use(cors());
app.use(routers.routes()).use(routers.allowedMethods())


// 静态资源
app.use(koaStatic(__dirname+'/public'))

// 由于配置https服务，因此此处暂且隐藏
// app.listen(config.port)

// console.log(config.port,`running...`)